<template>
  <view class="container">
    <van-sticky>
      <!-- 医院下拉选择框 -->
      <view class="hospital-dropdown" @click="showHospitalPicker = true">
        <view class="dropdown-content">
          <text class="dropdown-text">{{ selectedHospitalName || '全部院区' }}</text>
          <van-icon name="arrow-down" class="dropdown-icon" :class="{ 'rotate': showHospitalPicker }" />
        </view>
      </view>
      
      <van-search
        :value="searchKeyword"
        placeholder="搜索科室名字"
        @change="handleInput"
        @search="handleSearch"
      />
    </van-sticky>

    <!-- 医院选择下拉列表 -->
    <van-popup 
      v-model:show="showHospitalPicker" 
      position="top"
      :style="{ top: '88rpx' }"
      overlay-class="hospital-overlay"
    >
      <view class="hospital-list">
        <view 
          v-for="hospital in hospitals"
          :key="hospital.deptId"
          class="hospital-item"
          :class="{ 'active': selectedHospital?.deptId === hospital.deptId }"
          @click="selectHospital(hospital)"
        >
          <text class="hospital-name">{{ hospital.deptName }}</text>
          <van-icon v-if="selectedHospital?.deptId === hospital.deptId" name="success" color="#07C160" />
        </view>
      </view>
    </van-popup>

    <view class="department-list">
      <van-loading v-if="loading" type="spinner" color="#07C160" />
      <van-cell-group v-else>
        <van-cell
          v-for="department in filteredDepartments"
          :key="department.deptId"
          :title="department.deptName"
          :label="department.description"
          is-link
          @click="selectDepartment(department)"
        >
          <template #icon>
            <van-icon :name="getDepartmentIcon(department.deptName)" color="#07C160" />
          </template>
        </van-cell>
      </van-cell-group>
      
      <!-- 空状态 -->
      <van-empty v-if="!loading && filteredDepartments.length === 0" description="暂无科室数据" />
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from "vue";
import { onLoad } from "@dcloudio/uni-app";
import { getOneDeptList, getChildDeptList, type OneDepartment, type ChildDepartment } from "../../api/department";
import { useMedicalStore } from "@/stores/modules/medical"; // 新增导入

// 新增：创建medical store实例
const medicalStore = useMedicalStore();

const searchKeyword = ref("");
const loading = ref(false);
const showHospitalPicker = ref(false);

// 一级科室（医院）数据
const hospitals = ref<OneDepartment[]>([]);
const selectedHospital = ref<OneDepartment | null>(null);
const selectedHospitalName = ref(""); // 默认为空

// 子科室数据
const departments = ref<ChildDepartment[]>([]);

// 过滤后的科室列表
const filteredDepartments = computed(() => {
  if (!searchKeyword.value) {
    return departments.value;
  }
  return departments.value.filter(dept =>
    dept.deptName.includes(searchKeyword.value) ||
    dept.description.includes(searchKeyword.value)
  );
});

// 获取科室图标 - 优化后的版本
const getDepartmentIcon = (deptName: string) => {
  if (!deptName) return 'shop-o'; // 防止空名称
  
  const iconMap: Record<string, string> = {
    // 内科相关
    '内科': 'records',
    '心血管': 'like-o',
    '消化': 'records',
    '呼吸': 'records',
    '内分泌': 'records',
    '肾内': 'records',
    '神经内科': 'records',
    '血液': 'records',
    '风湿': 'records',
    '老年': 'records',
    
    // 外科相关
    '外科': 'logistics',
    '普外': 'logistics',
    '骨科': 'logistics',
    '泌尿': 'logistics',
    '胸外': 'logistics',
    '神经外科': 'logistics',
    '血管外科': 'logistics',
    '烧伤': 'logistics',
    '整形': 'logistics',
    
    // 妇产科
    '妇产': 'friends-o',
    '妇科': 'friends-o',
    '产科': 'friends-o',
    
    // 儿科
    '儿科': 'smile-o',
    '新生儿': 'smile-o',
    '小儿': 'smile-o',
    
    // 专科
    '眼科': 'eye-o',
    '耳鼻喉': 'phone-o',
    '口腔': 'smile-o',
    '皮肤': 'manager-o',
    '精神': 'manager-o',
    '康复': 'play-circle-o',
    
    // 中医科
    '中医': 'flower-o',
    '针灸': 'flower-o',
    '推拿': 'flower-o',
    
    // 肿瘤科
    '肿瘤': 'warning-o',
    '放疗': 'warning-o',
    '化疗': 'warning-o',
    '放射治疗': 'warning-o',
    
    // 感染科
    '感染': 'shield-o',
    '传染': 'shield-o',
    
    // 急诊科
    '急诊': 'phone-circle-o',
    '急救': 'phone-circle-o',
    'ICU': 'phone-circle-o',
    '重症': 'phone-circle-o',
    
    // 医技科室
    '检验': 'gold-coin-o',
    '病理': 'gold-coin-o',
    '影像': 'photo-o',
    '放射': 'photo-o',
    'CT': 'photo-o',
    'MRI': 'photo-o',
    'B超': 'photo-o',
    '超声': 'photo-o',
    
    // 其他
    '麻醉': 'play-circle-o',
    '药剂': 'gold-coin-o',
    '营养': 'gold-coin-o',
    '体检': 'medal-o',
    '健康': 'medal-o'
  };
  
  // 优先精确匹配
  if (iconMap[deptName]) {
    return iconMap[deptName];
  }
  
  // 模糊匹配 - 按长度排序，优先匹配长的关键词
  const sortedKeys = Object.keys(iconMap).sort((a, b) => b.length - a.length);
  
  for (const key of sortedKeys) {
    if (deptName.includes(key)) {
      return iconMap[key];
    }
  }
  
  // 默认图标
  return 'shop-o';
};
const handleInput = (e: any) => {
  searchKeyword.value = e.detail; // 注意是 e.detail，不是 e.detail.value
};

// 获取一级科室列表 - 使用Promise方式
const loadHospitals = () => {
  loading.value = true;
  
  getOneDeptList().then(response => {
    hospitals.value = response.data;
    
    // 默认选择第一个医院
    if (hospitals.value.length > 0) {
      selectedHospital.value = hospitals.value[0];
      selectedHospitalName.value = hospitals.value[0].deptName;
      
      // 新增：保存默认医院到pinia
      medicalStore.setCurrentHospital({
        deptId: hospitals.value[0].deptId,
        deptName: hospitals.value[0].deptName
      });
      
      // 自动加载该医院的子科室
      loadChildDepartments(hospitals.value[0].deptId);
    }
    loading.value = false;
  }).catch(error => {
    console.error('获取医院列表失败:', error);
    uni.showToast({
      title: '获取医院列表失败',
      icon: 'none'
    });
    loading.value = false;
  });
};

// 获取子科室列表 - 使用Promise方式
const loadChildDepartments = (parentId: string) => {
  loading.value = true;
  
  getChildDeptList(parentId).then(response => {
    departments.value = response.data;
    loading.value = false;
  }).catch(error => {
    console.error('获取科室列表失败:', error);
    uni.showToast({
      title: '获取科室列表失败',
      icon: 'none'
    });
    departments.value = [];
    loading.value = false;
  });
};

// 选择医院
const selectHospital = (hospital: OneDepartment) => {
  selectedHospital.value = hospital;
  selectedHospitalName.value = hospital.deptName;
  showHospitalPicker.value = false;
  
  // 新增：保存医院信息到pinia
  medicalStore.setCurrentHospital({
    deptId: hospital.deptId,
    deptName: hospital.deptName
  });
  
  // 加载选中医院的子科室
  loadChildDepartments(hospital.deptId);
};

// 搜索处理
const handleSearch = (val?: any) => {
  // search 事件的 detail 也是字符串，可直接用
  const keyword = typeof val === 'string' ? val : searchKeyword.value;
  console.log('搜索科室:', keyword);
};

// 选择科室
const selectDepartment = (department: ChildDepartment) => {
  const url = `/pages/appointment/doctor-select?departmentId=${department.deptId}&departmentName=${department.deptName}`;
  console.log('跳转到医生选择页面:', url);
  
  uni.navigateTo({
    url: url
  });
};

onLoad((options: Record<string, string>) => {
  console.log("选择科室页面 onLoad", options);
});

onMounted(() => {
  loadHospitals();
});
</script>

<style lang="scss">
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
}

.hospital-dropdown {
  background: white;
  padding: 24rpx 32rpx;
  border-bottom: 1px solid #ebedf0;
  
  .dropdown-content {
    display: flex;
    align-items: center;
    justify-content: space-between;
    
    .dropdown-text {
      font-size: 32rpx;
      color: #323233;
      font-weight: 500;
    }
    
    .dropdown-icon {
      font-size: 24rpx;
      color: #969799;
      transition: transform 0.3s ease;
      
      &.rotate {
        transform: rotate(180deg);
      }
    }
  }
}

.hospital-overlay {
  background: transparent;
}

.hospital-list {
  background: white;
  border-radius: 0 0 16rpx 16rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.1);
  max-height: 400rpx;
  overflow-y: auto;
  
  .hospital-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 24rpx 32rpx;
    border-bottom: 1px solid #f7f8fa;
    
    &:last-child {
      border-bottom: none;
    }
    
    &.active {
      background-color: #f2f3f5;
      
      .hospital-name {
        color: #07C160;
        font-weight: 500;
      }
    }
    
    .hospital-name {
      font-size: 28rpx;
      color: #323233;
    }
  }
}

.department-list {
  margin: 16rpx;
  border-radius: 16rpx;
  overflow: hidden;
  background: white;
  
  .van-loading {
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 80rpx 0;
  }
}
</style>